﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;

namespace INNOVACALL.Framework.Common.Serialization
{
    [XmlRoot("list")]
    [Serializable]
    public class SerializableList<T> : List<T>, IXmlSerializable
    {

        #region "Contructors"
        public SerializableList() : base() { }
        public SerializableList(IList<T> list) : base(list) { }
        public SerializableList(int capacity) : base(capacity) { }
        protected SerializableList(SerializationInfo info, StreamingContext context) { }
        #endregion
        #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }
        public void ReadXml(System.Xml.XmlReader reader)
        {
            XmlSerializer itemSerializer = new XmlSerializer(typeof(T));

            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();

            if (wasEmpty)
                return;

            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item");
                T item = (T)itemSerializer.Deserialize(reader);
                reader.ReadEndElement();

                this.Add(item);

                //reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }
        public void WriteXml(System.Xml.XmlWriter writer)
        {
            XmlSerializer itemSerializer = new XmlSerializer(typeof(T));

            foreach (T item in this)
            {
                writer.WriteStartElement("item");
                itemSerializer.Serialize(writer, item);
                writer.WriteEndElement();
            }
        }
        #endregion

        public Type ElementType
        {
            get { return this.AsQueryable<T>().ElementType; }
        }

        public System.Linq.Expressions.Expression Expression
        {
            get { return this.AsQueryable<T>().Expression; }

        }

        public IQueryProvider Provider
        {
            get { return this.AsQueryable<T>().Provider; }

        }
    }
}
